/**
 * 
 */
package com.solt.prism.core;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.xeoh.plugins.base.annotations.PluginImplementation;

import com.solt.prism.core.entity.News;
import com.sun.syndication.feed.synd.SyndEntry;

/**
 * @author thienlong
 * 
 */
@PluginImplementation
public class SimpleRssCrawler extends AbstractRssCrawler {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.solt.prism.core.AbstractRssCrawler#populate(com.solt.prism.core.entity
	 * .News, com.sun.syndication.feed.synd.SyndEntry)
	 */
	@Override
	protected boolean populate(News news, SyndEntry item) {
		Date creatTime = item.getPublishedDate();
		if (creatTime != null && !creatTime.after(lastAccessTime)) {
			return false;
		}
		news.setCreateTime(creatTime);
		news.setTitle(item.getTitle().trim());
		try {
			news.setSourceUrl(new URL(item.getLink().trim()));
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return false;
		}
		news.setCatId(currCat);
		String rawDesc = item.getDescription().getValue();
		news.setDescription(rawDesc.replaceAll("<.*?>", "").trim());
		Pattern imgPattern = Pattern.compile("<img.+?src=\"");
		Matcher matcher = imgPattern.matcher(rawDesc);
		if (matcher.find()) {
			int start = matcher.end();
			int end = rawDesc.indexOf('"', start);
			if (end > start) {
				try {
					URL url = new URL(homeSite, rawDesc.substring(start, end).trim());
					news.setImgUrl(url.toExternalForm());
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}

			}
		}
		return false;
	}
}
